package com.cinsea.ext;

import com.alibaba.fastjson.JSON;
import com.cinsea.common.*;
import com.cinsea.form.model.Formfield;
import com.cinsea.hrm.model.Human;
import com.cinsea.hrm.model.Org;
import com.cinsea.hrm.model.Orgtype;
import com.cinsea.hrm.model.Post;
import com.cinsea.hrm.service.HumanService;
import com.cinsea.hrm.service.OrgService;
import com.cinsea.hrm.service.OrgtypeService;
import com.cinsea.hrm.service.PostService;
import com.cinsea.htmlselect.model.Option;
import com.cinsea.htmlselect.service.OptionService;
import com.cinsea.log.model.Log;
import com.cinsea.log.service.LogService;
import com.cinsea.notify.model.Notifysetting;
import com.cinsea.security.LoginUser;
import com.cinsea.security.model.Right;
import com.cinsea.security.model.Role;
import com.cinsea.security.service.RightService;
import com.cinsea.security.service.RoleService;
import com.cinsea.security.util.JdbcUtil;
import com.cinsea.util.*;
import com.cinsea.workflow.model.Wfnode;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class ResearchAction extends ExtAction {
    public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String action = StringUtil.null2String(request.getParameter("action"));
        OptionService optionService = Env.getBean("optionService");
        RightService rightService = Env.getBean("rightService");
        JdbcDao jdbcDao = Env.getBean("jdbcDao");
        HumanService humanService = Env.getBean("humanService");
        OrgService orgService = Env.getBean("orgService");
        OrgtypeService orgtypeService = Env.getBean("orgtypeService");
        PostService postService = Env.getBean("postService");
        RoleService roleService = Env.getBean("roleService");
        LogService logService = Env.getBean("logService");
        if (action.equals("getrights")) {
            List options = optionService.getOptions2("1", null);
            boolean beone = false;
            if (options.size() == 1) beone = true;
            String objid = StringUtil.null2String(request.getParameter("objid"));
            String betype = StringUtil.null2String(request.getParameter("betype"));
            String tablename = StringUtil.null2String(request.getParameter("tablename"));
            String formid = StringUtil.null2String(request.getParameter("formid"));
            String opttype0 = StringUtil.null2String(request.getParameter("opttype"));
            String hsql = "SELECT * FROM cs_right WHERE objid =? AND betype=? AND opttype=? ORDER BY opttype,attachopttype,wfopttype,priority";
            Object[] params = new Object[]{objid, betype, opttype0};

            List list = rightService.find(hsql, params);

            if (betype.equals("0")) {
                hsql = "SELECT * FROM " + tablename + "_r WHERE objid= ? AND betype=? AND opttype=? ORDER BY opttype,attachopttype,wfopttype,priority";
                list.addAll(jdbcDao.getJdbcTemplate().query(hsql, new Object[]{objid, betype, opttype0}, new BeanPropertyRowMapper(Right.class)));
            }
            List ja = new ArrayList();
            for (int index = 0; index < list.size(); index++) {
                Map jo = new HashMap();
                Right right = (Right) list.get(index);
                String rightid = StringUtil.trimToNull(right.getId());
                String rightrange = StringUtil.trimToNull(right.getRightrange());
                String rolerange = StringUtil.trimToNull(right.getRolerange());
                String orgwhere = StringUtil.trimToNull(right.getOrgwhere());
                String userwhere = StringUtil.trimToNull(right.getUserwhere());
                String userids = StringUtil.trimToNull(right.getUserids());
                String orgid = StringUtil.trimToNull(right.getOrgid());
                String nodeforworkitem = StringUtil.trimToNull(right.getNodeforworkitem());
                String fieldid = StringUtil.trimToNull(right.getFieldid());
                String orgrange = StringUtil.trimToNull(right.getOrgrange());
                String roleid = StringUtil.trimToNull(right.getRoleid());
                String rolewhere = StringUtil.trimToNull(right.getRolewhere());
                String postrange = StringUtil.trimToNull(right.getPostrange());
                String orgtypeid = StringUtil.trimToNull(right.getOrgtype());

                String postwhere = StringUtil.trimToNull(right.getPostwhere());
                String postid = StringUtil.trimToNull(right.getPostid());
                String dimension = StringUtil.trimToNull(right.getDimension());
                String notifysettingid = StringUtil.trimToNull(right.getNotifysettingid());

                Integer beorgmanager = right.getBeorgmanager();
                Integer minlevel = right.getMinlevel();
                Integer maxlevel = right.getMaxlevel();
                Integer opttype = right.getOpttype();
                Integer attachopttype = right.getAttachopttype();
                Integer wfopttype = right.getWfopttype();

                String editviewid = right.getEditviewid();
                String readviewid = right.getReadviewid();
                Integer priority = right.getPriority();
                jo.put("id", right.getId());
                jo.put("betype", right.getBetype());
                jo.put("bedefault", right.getBedefault());
                jo.put("priority", priority);

                String opttypestr = "";
                if (opttype != null) {
                    List list1 = optionService.getOptions("12", null);
                    for (int i = 0; i < list1.size(); i++) {
                        Option _option = (Option) list1.get(i);
                        String optcode = StringUtil.null2String(_option.getObjdesc());
                        if (opttype.intValue() == NumberUtil.string2Int(optcode)) {
                            opttypestr += I18n.getText(StringUtil.null2String(_option.getObjname()));

                        }
                    }
                }


                jo.put("opttype", opttypestr);
                Option _option = optionService.get(rightrange);
                jo.put("rightrange", "&nbsp;" + I18n.getText(StringUtil.null2String(_option.getObjname())));
                String rightdesc = "";
                if ("11".equals(rightrange)) {
                    _option = optionService.get(userwhere);
                    rightdesc += I18n.getText(StringUtil.null2String(_option.getObjname())) + ":";
                    if ("26".equals(userwhere)) {
                        ArrayList arrUserids = StringUtil.string2ArrayList(userids, ",");
                        for (int i = 0; i < arrUserids.size(); i++) {
                            String _userid = "" + arrUserids.get(i);
                            Human human = (Human) humanService.getHumanById(_userid);
                            rightdesc += StringUtil.null2String(human.getObjname()) + "&nbsp;";
                        }
                    }
                } else if ("13".equals(rightrange)) {
                    _option = optionService.get(postwhere);
                    rightdesc += I18n.getText(StringUtil.null2String(_option.getObjname())) + ":";
                    if ("59".equals(postwhere)) {
                        Post post = postService.getPostByObjid(postid);
                        rightdesc += StringUtil.null2String(post.getObjname()) + "&nbsp;";
                    }
                } else if ("12".equals(rightrange)) {
                    rightdesc += I18n.getText("security") + I18n.getText("level") + ":";
                    if (minlevel != null)
                        rightdesc += "" + minlevel.intValue();
                    if (maxlevel != null)
                        rightdesc += "&nbsp;－&nbsp;" + maxlevel.intValue();
                } else if ("14".equals(rightrange)) {
                    _option = optionService.get(orgwhere);
                    rightdesc += I18n.getText(StringUtil.null2String(_option.getObjname())) + ":";
                    if ("31".equals(orgwhere)) {
                        ArrayList arrUserids = StringUtil.string2ArrayList(orgid, ",");
                        for (int i = 0; i < arrUserids.size(); i++) {
                            String _userid = "" + arrUserids.get(i);
                            Org org = (Org) orgService.getOrg(_userid);
                            rightdesc += StringUtil.null2String(org.getObjname()) + "&nbsp;";
                        }
                    }

                    rightdesc += "/" + I18n.getText("permissionrange") + ":";
                    _option = optionService.get(orgrange);
                    rightdesc += I18n.getText(StringUtil.null2String(_option.getObjname())) + "&nbsp;";

                    if (!"36".equals(orgrange) && !"37".equals(orgrange)) {
                        Orgtype orgtype = (Orgtype) orgtypeService.getOrgtype(orgtypeid);
                        rightdesc += StringUtil.null2String(orgtype.getObjname()) + "&nbsp;";
                    }
                    if (beorgmanager.equals(new Integer(0))) {
                        rightdesc += "/" + I18n.getText("security") + I18n.getText("level") + ":";
                        rightdesc += "" + minlevel.intValue();
                        if (maxlevel != null)
                            rightdesc += "&nbsp;－&nbsp;" + maxlevel.intValue();
                    } else
                        rightdesc += "/" + I18n.getText("department") + I18n.getText("manager");
                } else if ("15".equals(rightrange)) {


                    _option = optionService.get(postwhere);
                    rightdesc += I18n.getText(StringUtil.null2String(_option.getObjname())) + ":";
                    if ("59".equals(postwhere)) {
                        Post post = postService.getPostByObjid(postid);
                        rightdesc += StringUtil.null2String(post.getObjname()) + "&nbsp;";
                    }


                    _option = optionService.get(postrange);
                    rightdesc += "(" + I18n.getText(StringUtil.null2String(_option.getObjname())) + ")&nbsp;";

                    if ("68".equals(postrange)) {
                        Orgtype orgtype = (Orgtype) orgtypeService.getOrgtype(orgtypeid);
                        rightdesc += "&nbsp;" + StringUtil.null2String(orgtype.getObjname());
                    }
                    if ("67".equals(postrange)) {
                        _option = optionService.get(postrange);
                        rightdesc += "&nbsp;" + I18n.getText(StringUtil.null2String(_option.getObjname()));
                    }
                } else if ("16".equals(rightrange)) {


                    _option = optionService.get(postwhere);
                    rightdesc += I18n.getText(StringUtil.null2String(_option.getObjname())) + ":";
                    if ("59".equals(postwhere)) {
                        Post post = postService.getPostByObjid(postid);
                        rightdesc += StringUtil.null2String(post.getObjname()) + "&nbsp;";
                    }


                    _option = optionService.get(postrange);
                    rightdesc += "(" + I18n.getText(StringUtil.null2String(_option.getObjname())) + ")&nbsp;";
                } else if ("17".equals(rightrange)) {
                    if (rolewhere == null || "-1".equals(rolewhere)) {
                        rolewhere = "69";
                    }

                    _option = optionService.get(rolewhere);
                    rightdesc += I18n.getText(StringUtil.null2String(_option.getObjname())) + ":";
                    if ("69".equals(rolewhere) || "-1".equals(rolewhere)) {
                        Role sysrole = (Role) roleService.get(roleid);
                        rightdesc += StringUtil.null2String(sysrole.getObjname()) + "&nbsp;";
                    }
                    if ("1".equals(rolerange)) {
                        _option = optionService.get(orgwhere);
                        rightdesc += "/" + I18n.getText(StringUtil.null2String(_option.getObjname())) + ":";
                        if ("31".equals(orgwhere)) {
                            ArrayList arrUserids = StringUtil.string2ArrayList(orgid, ",");
                            for (int i = 0; i < arrUserids.size(); i++) {
                                String _userid = "" + arrUserids.get(i);
                                Org org = (Org) orgService.getOrg(_userid);
                                rightdesc += StringUtil.null2String(org.getObjname()) + "&nbsp;";
                            }
                        }

                    }

                }
                jo.put("rightdesc", rightdesc);

                ja.add(jo);

            }
            Map objectresult = new HashMap();
            objectresult.put("result", ja);

            response.getWriter().print(JSON.toJSONString(objectresult));
            return;
        }

        if (action.equals("unvoterlist")) {
            String objid = StringUtil.trimToNull(request.getParameter("objid"));
            String objmethod = StringUtil.trimToNull(request.getParameter("objmethod"));
            int pageNo = NumberUtil.string2Int(request.getParameter("pageno"), 1);
            int pageSize = NumberUtil.string2Int(request.getParameter("pagesize"), 20);
            if (!StringUtil.isEmpty(request.getParameter("start")))
                pageNo = NumberUtil.string2Int(request.getParameter("start"), 0) / pageSize + 1;

            StringBuffer basehql = new StringBuffer();
            if(objmethod.equals("402881ef39bd62d10139be7475680030"))
            basehql.append(" select distinct h.id userid,h.objname username ,o.id orgid,o.objname orgname,p.opttype opttype, h.seclevel seclevel,o.objorder objorder from  ut_research_d p,cs_human h,cs_org o")
                    .append(" where p.opttype='1493' and not exists(select 'X' from cs_log l where l.objid=p.objid and l.logtype='86' and l.submitor=h.id ) and  ((p.userid = h.id)  or (" + SqlUtil.isNotNull("p.postid") + " and h.postids like " + SqlUtil.concat("'%'", "p.postid", "'%'") + ") or (( p.alluser=1 or (" + SqlUtil.isNotNull("p.orgid") + " and h.orgid like " + SqlUtil.concat("'%'", "p.orgid", "'%'") + " )) ")
                    .append(" and (p.minlevel <= h.seclevel and ((p.maxlevel is not null and (h.seclevel<= p.maxlevel)) or p.maxlevel is null)")
                    .append("))) and p.objid = '").append(StringUtil.null2String(objid))
                    .append("' and h.orgid = o.id");
            else
                basehql.append(" select distinct h.id userid,h.objname username ,o.id orgid,o.objname orgname,p.opttype opttype, h.seclevel seclevel,o.objorder objorder from  ut_research_d p,cs_human h,cs_org o")
                                    .append(" where p.opttype='1493' and not exists(select 'X' from cs_log l where l.objtype=p.objid and l.logtype='82' and l.submitor=h.id ) and  ((p.userid = h.id)  or (" + SqlUtil.isNotNull("p.postid") + " and h.postids like " + SqlUtil.concat("'%'", "p.postid", "'%'") + ") or (( p.alluser=1 or (" + SqlUtil.isNotNull("p.orgid") + " and h.orgid like " + SqlUtil.concat("'%'", "p.orgid", "'%'") + " )) ")
                                    .append(" and (p.minlevel <= h.seclevel and ((p.maxlevel is not null and (h.seclevel<= p.maxlevel)) or p.maxlevel is null)")
                                    .append("))) and p.objid = '").append(StringUtil.null2String(objid))
                                    .append("' and h.orgid = o.id");
            Page pageObject = jdbcDao.pagedQuery(basehql.toString(), pageNo, pageSize);


            List list = new ArrayList();
            if (pageObject.getTotalSize() != 0) {
                list = (List) pageObject.getResult();
            }
            List arrayjson = new ArrayList();


            for (Object row : list) {
                Map object = new HashMap();
                String userid = (String) ((Map) row).get("userid");
                String username = (String) ((Map) row).get("username");

                object.put("username", "<a href=\"javascript:onUrl('/form/formprocess.jsp?processid=" + userid + "','" + username + "','tab" + userid + "')\" >" + username + "</a>");

                arrayjson.add(object);
            }//end for
            Map jsonresult = new HashMap();
            jsonresult.put("totalcount", pageObject.getTotalSize());
            jsonresult.put("result", arrayjson);
            response.getWriter().print(JSON.toJSONString(jsonresult));
            return;
        }

        if (action.equals("voterlist")) {
            String objid = StringUtil.trimToNull(request.getParameter("objid"));
            String objmethod = StringUtil.null2String(request.getParameter("objmethod"));
            int pageNo = NumberUtil.string2Int(request.getParameter("pageno"), 1);
            int pageSize = NumberUtil.string2Int(request.getParameter("pagesize"), 20);
            if (!StringUtil.isEmpty(request.getParameter("start")))
                pageNo = NumberUtil.string2Int(request.getParameter("start"), 0) / pageSize + 1;

            Map filter = new HashMap();
            if(objmethod.equals("402881ef39bd62d10139be7475680030")){
            filter.put("objid", objid);
            filter.put("logtype", "86");
            }else{
                filter.put("objid", objid);
                filter.put("logtype", "82");

            }
            Page pageObject = logService.getPagedByQuery(filter, pageNo, pageSize);
            List list = new ArrayList();
            if (pageObject.getTotalSize() != 0) {
                list = (List) pageObject.getResult();
            }
            List arrayjson = new ArrayList();
            for (Object row : list) {
                Map object = new HashMap();
                String userid = ((Log) row).getSubmitor();
                String username = humanService.getHumanById(userid).getObjname();
                object.put("username", "<a href=\"javascript:onUrl('/form/formprocess.jsp?processid=" + userid + "','" + username + "','tab" + userid + "')\" >" + username + "</a>");
                arrayjson.add(object);
            }//end for
            Map jsonresult = new HashMap();
            jsonresult.put("totalcount", pageObject.getTotalSize());
            jsonresult.put("result", arrayjson);
            response.getWriter().print(JSON.toJSONString(jsonresult));
            return;
        }

        if (action.equals("myresearch")) {
            String objname = StringUtil.trimToNull(request.getParameter("objname"));

            int pageNo = NumberUtil.string2Int(request.getParameter("pageno"), 1);
            int pageSize = NumberUtil.string2Int(request.getParameter("pagesize"), 20);
            if (!StringUtil.isEmpty(request.getParameter("start")))
                pageNo = NumberUtil.string2Int(request.getParameter("start"), 0) / pageSize + 1;

            String sql = "select * from ut_research where deleted=0";
            if (!StringUtil.isEmpty(objname)) {
                sql += " and objname like '%" + objname + "%'";
            }
            sql += " order by startdate desc,starttime desc";
            String newsql = JdbcUtil.getPermissionSql(sql, "ut_research");
            Page pageObject = jdbcDao.pagedQuery(newsql, pageNo, pageSize);


            List list = new ArrayList();
            if (pageObject.getTotalSize() != 0) {
                list = (List) pageObject.getResult();
            }
            List arrayjson = new ArrayList();


            for (Object row : list) {
                Map object = new HashMap();
                String processid = (String) ((Map) row).get("processid");
                String researchname = (String) ((Map) row).get("objname");
                String objmethod = (String) ((Map) row).get("objmethod");
                long righttype = rightService.getOpttype(processid, "", "ut_research");
                if (righttype % OptType.VIEW == 0) {
                    researchname = "<a href=\"javascript:onUrl('/research/researchview.jsp?processid=" + processid + "','" + researchname + "','tab" + processid + "')\" >" + researchname + "</a>";
                }
                object.put("objname", researchname);
                String _objdesc = (String) ((Map) row).get("objdesc");
                object.put("objdesc", _objdesc);
                String _startdate = (String) ((Map) row).get("startdate");
                object.put("startdate", _startdate);
                String _starttime = (String) ((Map) row).get("starttime");
                object.put("starttime", _starttime);
                String _enddate = (String) ((Map) row).get("enddate");
                object.put("enddate", _enddate);
                String _endtime = (String) ((Map) row).get("endtime");
                object.put("endtime", _endtime);
                String _objmethod = (String) ((Map) row).get("objmethod");
                String currenttime= DateUtil.getCurDateTime();
                boolean expired=false;
                if(currenttime.compareTo(_startdate+" "+_starttime)<0||currenttime.compareTo(_enddate+" "+_endtime)>0) expired=true;
                boolean logflag = false;
                if (_objmethod.equals("402881ef39bd62d10139be7475680030") && logService.hasLog(processid, Env.getRemoteUser().getId(), "86"))//问卷
                    logflag = true;
                else {//表单
                    List logs = logService.find("from Log where logtype='82' and submitor='" + Env.getRemoteUser().getId() + "' and objtype='" + processid + "'");
                    if (logs.size() > 0) logflag = true;
                }
                if (righttype % 1493 == 0 && !logflag&&!expired) {
                    String action1 = "<a href=\"javascript:showResearch('" + processid + "','" + objmethod + "')\" >" + "投票" + "</a>";
                    object.put("action1", action1);
                }
                if (righttype % 1499 == 0) {
                    String action2 = "<a href=\"javascript:showResearchresult('" + processid + "','" + objmethod + "')\" >" + "查看结果" + "</a>";
                    object.put("action2", action2);
                }
                arrayjson.add(object);
            }//end for
            Map jsonresult = new HashMap();
            jsonresult.put("totalcount", pageObject.getTotalSize());
            jsonresult.put("result", arrayjson);
            response.getWriter().print(JSON.toJSONString(jsonresult));
            return;
        }
    }
}
